package com.three.storemanage.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.three.core.entity.CouponCodes;
import com.three.core.entity.User;
import com.three.core.vo.R;
import com.three.storemanage.feign.UserFeign;
import com.three.storemanage.mapper.CouponCodesMapper;
import com.three.storemanage.service.CouponCodesService;
import com.three.storemanage.vo.SearchForm;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @FileName: CouponCodesServiceImpl
 * @Description:
 * @Author: GYX
 * @CreateTime: 2025/3/14 9:52
 * @Version: 1.0.0
 */
@Service
public class CouponCodesServiceImpl implements CouponCodesService {
    @Autowired
    private CouponCodesMapper couponCodesMapper;
    @Autowired
    private UserFeign userFeign;
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private HttpServletRequest request;
    @Override
    public R<Page<CouponCodes>> findCouponCodesByCondition(SearchForm searchForm) {
        String token = request.getHeader("token");
        Object userName = redisTemplate.opsForHash().get("user::login::" + token, "name");
        R<User> feign = userFeign.getByName((String) userName);
        User user = feign.getData();
        Integer userId = user.getUserId();
        Page<CouponCodes> page = new Page<>(searchForm.getCurrentPage(), searchForm.getPageSize());
        Page<CouponCodes> records = couponCodesMapper.findCouponCodesByCondition(page,searchForm.getStoreName(),userId);
        return new R<>(200,"查询成功",records);

    }

    @Override
    public R deleteCouponCodesById(Integer couponId) {
        int i = couponCodesMapper.deleteById(couponId);
        if (i>0){
            return new R(200,"删除成功",null);
        }else {
            return new R(500,"删除失败",null);
        }
    }

    @Override
    public R insertCouponCodes(CouponCodes couponCodes) {
        String token = request.getHeader("token");
        Object userName = redisTemplate.opsForHash().get("user::login::" + token, "name");
        R<User> feign = userFeign.getByName((String) userName);
        User user = feign.getData();
        Integer userId = user.getUserId();
        couponCodes.setUserId(userId);
        couponCodes.setCreationDate(new Date());
        int i = couponCodesMapper.insertSelective(couponCodes);
        if (i>0){
            return new R(200,"添加成功",null);
        }else {
            return new R(500,"添加失败",null);
        }
    }

    @Override
    public R updateCouponCodes(CouponCodes couponCodes) {
        int i = couponCodesMapper.updateByPrimaryKeySelective(couponCodes);
        if (i>0){
            return new R(200,"修改成功",null);
        }else {
            return new R(500,"修改失败",null);
        }
    }
}
